package com.evan.jdbc;

import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @ClassName: JdbcUtil 
 * @Description: JDBC的工具类(从配置文件中读取信息)、创建连接、关闭连接
 * @author Evan 
 * @date 2017年4月13日 下午12:38:57 
 *
 */
public class JdbcUtil {
    
//    private static final String DRIVATE_NAME = "com.mysql.jdbc.Driver";
//    private static final String URL = "jdbc:mysql://localhost:3306/taotao";
//    private static final String USER = "root";
//    private static final String PASSWORD = "123456";
    
    /*
     * 从配置文件中读取
     */
    private static final String DRIVATE_NAME ;
    private static final String URL ;
    private static final String USER ;
    private static final String PASSWORD ;
    
    static{
        Properties prop = new Properties();
        Reader in;
        try{
            in = new FileReader("src/congfig.properties");
            prop.load(in);
        }catch(Exception e){
            e.printStackTrace();
        }
        DRIVATE_NAME = prop.getProperty("DRIVATE_NAME");
        URL = prop.getProperty("URL");
        USER = prop.getProperty("USER");
        PASSWORD = prop.getProperty("PASSWORD");
    }
    
    /**
     * 创建连接
     */
    public static Connection openConn(){
        //加载驱动
        try {
            Class.forName(DRIVATE_NAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        
        //创建连接
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     */
    public static void closeConn(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
